<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input v-model="query.taskName" class="filter-item" style="width: 200px" placeholder="请输入任务名称" clearable @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.status" class="filter-item" placeholder="请选择迁移状态" filterable clearable style="width:200px">
          <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!-- 功能按钮 -->
      <crudOperation :permission="permission" />
    </div>
    <!-- 数据列表 -->
    <el-table
      ref="table"
      v-loading="crud.loading"
      style="width: 100%;"
      :data="crud.data"
      @filter-change="crud.handleFilterChange"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column v-if="columns.visible('taskName')" :show-overflow-tooltip="true" prop="taskName" label="任务名称" min-width="150" />
      <el-table-column v-if="columns.visible('migrationType')" :show-overflow-tooltip="true" prop="migrationType" label="迁移类型" min-width="150" />
      <el-table-column v-if="columns.visible('transferType')" prop="transferType" label="迁移方式">
        <template slot-scope="scope">
          {{ formatterTransferType(scope.row.transferType) }}
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('status')" label="迁移状态" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'TODO'" type="info">待迁移</el-tag>
          <el-tag v-if="scope.row.status === 'PROCESSING'">迁移中</el-tag>
          <el-tag v-if="scope.row.status === 'FINISH'" type="success">完成</el-tag>
          <el-tag v-if="scope.row.status === 'FAIL'" type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('total')" prop="total" label="迁移进度" min-width="280">
        <template slot-scope="scope">
          <el-tag type="info">总数：{{ scope.row.total }}</el-tag>
          <el-tag type="success" style="margin: 0px 5px">迁移成功: {{ scope.row.successCount }}</el-tag>
          <el-tag type="danger">迁移失败: {{ scope.row.failCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('startTime')" prop="startTime" label="开始时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.startTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('endTime')" prop="endTime" label="结束时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.endTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('upUserName')" prop="upUserName" label="更新人" />
      <el-table-column v-if="columns.visible('upTs')" prop="upTs" label="更新时间" min-width="150" />
      <el-table-column label="详情">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="toShowDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination />
    <!-- 新增页面 -->
    <el-dialog
      v-if="crud.status.cu > 0"
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      title="数据迁移"
      width="1200px"
      top="5vh"
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="150px">
        <el-row>
          <el-col :span="22">
            <el-steps :active="active" finish-status="success" simple>
              <el-step title="基本信息" />
              <el-step title="迁移结果" />
            </el-steps>
          </el-col>
          <el-col :span="2">
            <div class="grid-content bg-purple-light">
              <el-button icon="el-icon-question" class="assist" @click="helpFormVisible = true">帮助</el-button>
            </div>
          </el-col>
        </el-row>
        <div v-if="active === 0">
          <create-task v-if="active === 0" ref="basicInfo" v-model="form" :crud="crud" />
          <div slot="footer" class="dialog-footer" style="width:100%;text-align: center;margin-top: 10px">
            <el-button @click="crud.cancelCU()">关 闭</el-button>
            <el-button type="primary" :class="{btnDisabled: form.isHiddenValu}" @click="save">保存</el-button>
            <el-button type="primary" @click="toConvert">下一步(保存并同步)</el-button>
          </div>
        </div>
        <div v-if="active === 1">
          <transfer-result v-if="active === 1" :data-transfer-task-pk-id="dataTransferTaskPkId" />
          <div class="dialog-footer" style="width:100%;text-align: center;margin-top: 40px">
            <el-button type="primary" @click="back">上一步</el-button>
            <el-button type="primary" @click="crud.cancelCU()">关闭</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看帮助文档 -->
    <el-dialog title="帮助" :visible.sync="helpFormVisible" width="1200px">
      <div>
        <data-transfer-helper />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/expand/data/transfer/CRUD.operation'
import pagination from '@crud/Pagination'
import dataTransferTaskApi from '@/api/data/transfer/dataTransferTask'
import validateTaskName from '@/utils/taskNameRepeat'
import createTask from './components/create-task/create-task.vue'
import transferResult from './components/transfer-result/transfer-result.vue'
import dataTransferHelper from './components/helper/helper.vue'
import dataTransferList from '@/api/data/transfer/dataTransferList'
import dataSourceApi from '@/api/metadata/dataSource'

const defaultCrud = CRUD({ title: '数据迁移任务', url: '/api/data/transfer/task', crudMethod: { ...dataTransferTaskApi }})
const defaultForm = {
  pkId: null,
  taskName: null,
  tableSelectType: '直连',
  dataSyncType: 'TODAY',
  dataTransferType: 'DataX',
  textSourceConnPkId: null,
  sourceConnPkId: null,
  database: null,
  dataSyncStartTime: null,
  dataSyncEndTime: null,
  status: 'TODO',
  total: 0,
  successCount: 0,
  failCount: 0,
  isDataAnalysis: 'N',
  tableList: [],
  transferType: 'ExpandNum',
  isHiddenValu: false
}
export default {
  components: { dataTransferHelper, crudOperation, rrOperation, pagination, createTask, transferResult },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      dataTransferTaskPkId: null,
      dataTransferType: 'Jdbc',
      taskPkId: '',
      active: 0,
      helpFormVisible: false,
      permission: {
        add: ['admin', 'dataTransfer:add'],
        edit: ['admin', 'dataTransfer:edit'],
        del: ['admin', 'dataTransfer:del']
      },
      statusOptions: [
        { key: 'TODO', label: '待迁移' },
        { key: 'PROCESSING', label: '迁移中' },
        { key: 'FINISH', label: '完成' },
        { key: 'FAIL', label: '失败' }
      ],
      rules: {
        taskName: [
          { required: true, validator: validateTaskName.bind(this, dataTransferTaskApi, this.form), trigger: 'blur' }
        ],
        // tableSelectType: [
        //   { required: true, message: '请选择表选择方式', trigger: 'change' }
        // ],
        // sourceConnPkId: [
        //   { required: true, message: '请选择服务名称', trigger: 'change' }
        // ],
        // database: [
        //   { required: true, message: '请选择数据库名称', trigger: 'blur' }
        // ],
        // dataSyncType: [
        //   { required: true, message: '请选择日期', trigger: 'change' }
        // ],
        // customTime: [
        //   { required: true, message: '请选择自定义日期', trigger: 'change' }
        // ]
      }
    }
  },
  created() {
    this.crud.resetQuery(false)
  },
  methods: {
    // 数据迁移创建任务按钮点击钩子回调
    [CRUD.HOOK.beforeToAdd](crud) {
      this.form = crud.form
      this.active = 0
    },
    // 数据迁移编辑任务按钮点击钩子回调
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.form = crud.form
      if (this.form.status === 'TODO') {
        this.form.isHiddenValu = false
        this.active = 0
      } else {
        this.dataTransferTaskPkId = this.form.pkId
        this.form.isHiddenValu = true
        this.active = 1
      }
      // 用于编辑功能时获取任务名称
      this.form.validateName = this.form.taskName
      this.taskPkId = form.pkId
      const param = {
        'dataTransferTaskPkId': form.pkId
      }
      this.getEditInfo(param)
    },
    async getEditInfo(param) {
      let data1, data2
      const param2 = { size: 500, status: 'ENABLE' }
      try {
        data1 = await dataSourceApi.findListByPage(param2)
      } catch (error) {
        this.crud.notify('获取源/目标服务器失败！', 'error')
        return
      }
      try {
        data2 = await dataTransferList.findListByPage(param)
      } catch (error) {
        this.crud.notify('获取数据迁移列表失败！', 'error')
        return
      }
      this.sourceConnList = data1.content
      this.form.tableList = data2.content
      if (this.form.tableList.length) {
        this.form.sourceConnPkId = this.form.tableList[0].sourceConnPkId
        this.form.database = this.form.tableList[0].sourceDatabaseName
        this.form.tableList.forEach(item => {
          this.sourceConnList.forEach(item2 => {
            if (item2.pkId === item.sourceConnPkId) {
              item.sourceConnName = item2.sourceName
            }
            if (item2.pkId === item.targetConnPkId) {
              item.targetConnName = item2.sourceName
            }
          })
        })
      }
    },
    formatterTransferType(val) {
      if (val === 'ExpandNum') {
        return '直连载数'
      } else if (val === 'TextLoad') {
        return '文本载数'
      } else if (val === 'UnloadText') {
        return '文本卸数'
      }
      return '直连载数'
    },
    async toShowDetail(row) {
      this.form = row
      this.dataTransferTaskPkId = this.form.pkId
      const param = {
        'dataTransferTaskPkId': this.dataTransferTaskPkId
      }
      await this.getEditInfo(param)
      if (this.form.status === 'TODO') {
        this.form.isHiddenValu = true
        this.active = 0
      } else {
        this.active = 1
      }
      this.crud.status.edit = 1
    },
    checkHasTableList() {
      if (this.crud.form.tableList.length === 0) {
        this.$notify({
          title: '请至少选择一个迁移数据表！',
          type: 'error',
          duration: 2500
        })
        return false
      }
      return true
    },
    // 保存
    save() {
      if (!this.form.isHiddenValu) {
        this.$refs['form'].validate((validate) => {
          if (validate && this.checkHasTableList()) {
            dataTransferTaskApi.edit(this.form).then((res) => {
              this.crud.notify(res, CRUD.NOTIFICATION_TYPE.SUCCESS)
              this.crud.cancelCU()
              this.crud.refresh()
            }).catch(err => {
              console.log(err)
            })
          }
        })
      }
    },
    // 保存并同步
    toConvert() {
      if (this.form.isHiddenValu) {
        this.active++
      } else {
        this.$refs['form'].validate((validate) => {
          if (validate && this.checkHasTableList()) {
            if (this.form.customTime && this.form.customTime.length !== 0) {
              this.form.dataSyncStartTime = this.form.customTime[0]
              this.form.dataSyncEndTime = this.form.customTime[1]
            }
            this.$notify({
              title: '数据正在迁移中,请等候',
              type: 'success',
              duration: 2500
            })
            dataTransferTaskApi.updateWithSync(this.form).then((res) => {
              this.dataTransferTaskPkId = res
              this.crud.refresh()
              this.active++
            })
          } else {
            return false
          }
        })
      }
    },
    back() {
      this.form.isHiddenValu = true
      this.active--
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-transfer-panel {
  width: 250px;
}

::v-deep .bordered-button {
  border: #92dab3 2px;
}

::v-deep .el-transfer__buttons button {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .el-transfer__buttons button:first-child span span {
  margin-left: 0px;
}

.assist {
  min-height: 46px;
  color: #fff;
  background-color: #ff4949;
  border-color: #ff4949;
}
.btnDisabled{
  color: #FFF;
  cursor: not-allowed;
  background-color: #f3d19e;
  border-color: #f3d19e;
}
</style>
